package gen

import (
	"fmt"
	"game/game-design/export"
	"os"
	"strings"
)

func Generate(args []string) {
	genArgs := NewGenArgs(args)
	if !genArgs.Check() {
		fmt.Println("缺少必要运行参数")
		return
	}
	fileList, err := os.ReadDir(genArgs.SourceHome)
	if err != nil {
		fmt.Println(err)
		return
	}
	lines := ReadTemplateFile(genArgs.TemplateFile)

	var readerIO export.IDesignIO = genArgs.Reader
	for _, f := range fileList {
		if strings.HasPrefix(f.Name(), "~$") {
			continue
		}
		if f.IsDir() {
			continue
		}
		fileFullPath := genArgs.SourceHome + string(os.PathSeparator) + f.Name()
		designFiles, err := readerIO.Read(fileFullPath, genArgs.DesignDefine)
		if err != nil {
			fmt.Println(err)
			continue
		}
		designFile := designFiles[0]

		CurrFile = designFile.Name
		Params["classMeta"] = designFile

		classBlocks := NewClassBlock(lines)
		for _, clazz := range classBlocks {
			os.Mkdir(clazz.FileDir, 0755)
			content := clazz.BuildResult()

			if clazz.GenIfAbsent {
				_, err := os.Stat(clazz.FileDir + clazz.FileName)
				if err != nil && os.IsNotExist(err) {
					fmt.Println("导出代码=>\t", clazz.FileName)
					err := os.WriteFile(clazz.FileDir+clazz.FileName, []byte(content), 0666)
					if err != nil {
						fmt.Println(err)
					}
				}
			} else {
				fmt.Println("导出代码=>\t", clazz.FileName)
				err := os.WriteFile(clazz.FileDir+clazz.FileName, []byte(content), 0666)
				if err != nil {
					fmt.Println(err)
				}
			}
		}
	}
}
